package com.fourfaith.iot.beidou.handler;

import com.fourfaith.iot.beidou.decodec.BeiDouCodec;
import com.fourfaith.iot.beidou.decodec.BeiDouFrameDecoder;
import com.fourfaith.iot.device.cloud.access.dubbo.service.IBeidouDubboService;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Name ChildChannelHandler
 * @Description 子通道处理程序
 * @Author shiyunan
 * @Create 2021/11/10 16:14
 */
@Slf4j
public class ChannelInitializerHandler extends ChannelInitializer<SocketChannel> {

    LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);

    private static IBeidouDubboService beidouDubboService;

    public ChannelInitializerHandler(IBeidouDubboService beidouDubboService){
        this.beidouDubboService = beidouDubboService;
    }

    @Override
    public void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        // 用来判断是不是 读空闲时间过长 或者 写空闲时间过长
        // 30s 内如果没有收到channel的数据，会触发一个 IdleStateEvent 事件(IdleState#READER_IDLE)
        pipeline.addLast(new IdleStateHandler(30,30,0));
        // ChannelDuplexHandler 可以同时作为入站和出站处理器 ，建立连接和断开连接异常事件处理
        pipeline.addLast(new SpecialEventHandler());
        pipeline.addLast(LOGGING_HANDLER);
        pipeline.addLast(new BeiDouFrameDecoder(2048));
        pipeline.addLast(new BeiDouCodec());
        pipeline.addLast(new BDtciMessageHandler(beidouDubboService));
        pipeline.addLast(new BDpwiMessageHandler());
        pipeline.addLast(new BDicpMessageHandler());
        pipeline.addLast(new BDfkiMessageHandler());

    }

}